//
//  ObjectMapper+Extention.swift
//  TeaShop
//
//  Created by 刘泽 on 2018/1/14.
//  Copyright © 2018年 刘泽. All rights reserved.
//


import Foundation
@_exported
import ObjectMapper
import RxSwift
import Moya
public extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    
    /// Maps data received from the signal into an object
    /// which implements the Mappable protocol and returns the result back
    /// If the conversion fails, the signal errors.
    public func mapObject<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<T> {
        return flatMap { response -> Single<T> in
            return Single.just(try response.mapObject(type, context: context))
        }
        
    }



    public func mapArr<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Single<[T]> {
        return flatMap { response -> Single<[T]> in
            return Single.just(try response.mapArray(type, context: context))
        }
    }



}

public extension Response {
    public func mapObject<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) throws -> T {
        
        guard let object = Mapper<T>(context: context).map(JSONObject: try mapJSON()) else {
            throw MoyaError.jsonMapping(self)
        }

        guard let res = response else{
            let err = MyError()
            err.status = -1001
            throw err
        }

        switch res.statusCode {
        case 200:
            break
        case 400:
            let erro = MyError()
            erro.status = 400
            erro.error = "参数错误"
            throw erro
        default:
            let erro = MyError()
            erro.status = 400
            erro.error = "未知错误"
            throw erro
        }

        return object
        
    }

    /// Maps data received from the signal into an array of objects which implement the Mappable
    /// protocol.
    /// If the conversion fails, the signal errors.
    public func mapArray<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) throws -> [T] {
        guard let array = try mapJSON() as? [[String : Any]] else {
            throw MoyaError.jsonMapping(self)
        }
        return Mapper<T>(context: context).mapArray(JSONArray: array)
    }


}





